﻿using Farming.Domain.Dtos;
using Farming.Domain.Entities;
using Farming.Repositories;
using IdentityModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Panda.DynamicWebApi;
using Panda.DynamicWebApi.Attributes;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Farming.Application.Admins
{
    [DynamicWebApi]
    [ApiExplorerSettings(GroupName = "v1")]
    [Authorize]
    public class AdminDataService : IDynamicWebApi, IAdminDataService
    {
        private readonly IRepository<Admin> adminRep;
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IConfiguration configuration;
        private static string userName;
        private static string userId;
        public AdminDataService(IRepository<Admin> adminRep, IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
        {
            this.adminRep = adminRep;
            this.httpContextAccessor = httpContextAccessor;
            this.configuration = configuration;
            userName = httpContextAccessor.HttpContext.User.FindFirst(JwtClaimTypes.Name)?.Value;
        }
        public List<Admin> GetAdminList()
        {
            var list = new List<Admin>();
            list.Add(new Admin
            {
                AdminId = 1,
                UserName = "tt",
                PassWord = "123456",
                LastLoginIp = "北京顺义区",
                LastLoginTime = DateTime.Now,
                CreateById = 1,
                CreateByName = "张三",
                CreateTime = DateTime.Now,
                IsDel = false,
            });
            list.Add(new Admin
            {
                UserName = "tangtang",
                PassWord = "123456",
                LastLoginIp = "北京大兴区",
                LastLoginTime = DateTime.Now,
                CreateById = 1,
                CreateByName = "张三",
                CreateTime = DateTime.Now,
                IsDel = false,
            });
            list.Add(new Admin
            {
                UserName = "yy",
                PassWord = "123456",
                LastLoginIp = "天津河东区还是河西区忘了",
                LastLoginTime = DateTime.Now,
                CreateById = 1,
                CreateByName = "张三",
                CreateTime = DateTime.Now,
                IsDel = false,
            });
            return list;
        }
        public async Task<int> Regist(Admin admin)
        {
            return await adminRep.AddAsync(admin);
        }
        public object GetMd5(string source)
        {
            var md5= MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(source));
            return BitConverter.ToString(md5).Replace("-","").ToUpper();
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<LoginResponseDto<string>> Login(LoginRequestDto request)
        {
            try
            {
                LoginResponseDto<string> response = new LoginResponseDto<string>();
                var pwd= request.PassWord= GetMd5(request.PassWord).ToString();
                var list = await adminRep.GetByIdAsync(x => x.UserName == request.UserName&&x.PassWord==pwd);
                if (list == null)
                {
                    // 如果没有找到符合条件的用户
                    var listyUsername = await adminRep.GetValueAsync(x => x.UserName == request.UserName);
                    if (listyUsername==null||!listyUsername.Any())
                    {
                        response.Code = Status.Failed;
                        response.Message = "用户不存在";
                    }
                    else
                    {
                         response.Code = Status.Failed;
                         response.Message = "密码错误";
                    } 
                }
                else
                {
                    // 如果找到符合条件的用户

                    //调用生成Token方法
                    var token = GenerateToken(list);

                    response.Code = Status.Success;
                    response.Message = "登录成功";
                    response.Token=token.Token;
                    response.Claims= token.Claims;

                    list.LastLoginIp=httpContextAccessor.HttpContext.Connection.RemoteIpAddress.
                    MapToIPv4().ToString();
                    list.LastLoginTime=DateTime.Now;
                    adminRep.UpdAsync(list);
                }
                return response;
            }
            catch (Exception)
            {

                throw;
            }
           
            
        }
       
        //public async Task<string> GetAdmin()
        //{
        //    var userName = httpContextAccessor.HttpContext.User.Identity.Name;
        //    var s = httpContextAccessor.HttpContext.User.Identities.FirstOrDefault();
        //    var Id = httpContextAccessor.HttpContext.User;
        //    var http=httpContextAccessor.HttpContext.User.FindFirst(JwtClaimTypes.Name)?.Value;
        //    return http;
        //}
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="adminId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<int> DelAdminAsync(int adminId)
        {
            try
            {
                var list = await adminRep.GetValueAsync(x => x.AdminId == adminId);
                list.ForEach(z =>
                {
                    z.IsDel = true;
                    z.UpdTime = DateTime.Now;
                    z.UpdById = adminId;
                    //z.UpdByName = z.UserName;
                    adminRep.UpdAsync(z);
                });
                return 1;

            }
            catch (Exception)
            {

                throw;
            }
        }
        
        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="admin"></param>
        /// <returns></returns>
        private LoginResponseDto<string> GenerateToken(Admin admin)
        {
            IList<Claim> claims = new List<Claim> 
            {
                        new Claim(JwtClaimTypes.Id,admin.AdminId.ToString()),
                        new Claim(JwtClaimTypes.Name,admin.UserName),
            };

            var identity=new ClaimsIdentity(claims,"login");
            var claimsPrincipal = new ClaimsPrincipal(identity);
            httpContextAccessor.HttpContext.User=claimsPrincipal;//确保User被正确设置

            // 将Claim转为字符串列表
            var claimStrings = claims.Select(c => $"{c.Type}: {c.Value}").ToList();

            //JWT密钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtConfig:Bearer:SecurityKey"]));

            //算法
            var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //过期时间
            DateTime expires = DateTime.UtcNow.AddHours(30);


            //Payload负载
            var token = new JwtSecurityToken(
                issuer: configuration["JwtConfig:Bearer:Issuer"],
                audience: configuration["JwtConfig:Bearer:Audience"],
                claims: claims,
                notBefore: DateTime.UtcNow,
                expires: expires,
                signingCredentials: cred
                );

            var handler = new JwtSecurityTokenHandler();

            //生成令牌
            string jwt = handler.WriteToken(token);

            //令牌续期(生成两个令牌，一个访问令牌使用，一个交换令牌留着换令牌)
            //--jwt没有这个，用其他方法做,eg:前端的响应拦截器（前端无痛刷新）

            return new LoginResponseDto<string>
            { 
                Token = jwt,
                Claims=claimStrings,
            };

        }
    }
}
